<template>
  <el-card class="elcard" style="flex:1;align-self:normal;">
    <div slot="header" class="hd clearfix">
      <p class="tit">关联企业图谱</p>
    </div>
    <div id="atlas" :style="chartStyle"></div>
    <div v-if="Object.keys(this.data).length <= 0" class="no-data">
      <loading1 :emptyText="emptyText"/>
    </div>
  </el-card>
</template>

<script>
export default {
  data() {
    return {
      info: {},
      data: {},
      emptyText: 'loading'
    }
  },
  computed: {
    // 图表样式
    chartStyle() {
      if (Object.keys(this.data).length > 0) {
        return {
          position: 'relative'
        }
      } else {
        return {
          position: 'absolute',
          top: '-9999px',
          left: '-9999px',
          'z-index': -1
        }
      }
    }
  },
  methods: {
    init() {
      this.info = {
        name: this.$route.query.name,
        key: this.$route.query.key,
        companyName: this.$route.query.companyName
      }
      this.initNode()
      this.getData()
      // this.renderChart()
    },
    initNode() {
      const { Util } = G6
      // 根节点
      G6.registerNode(
        'dice-mind-map-root', {
          jsx: (cfg) => {
            const width = Util.getTextSize(cfg.label, 16)[0] + 24;
            const stroke = cfg.style.stroke || '#DAE2E4';
            // const fill = cfg.style.fill || '#DAE2E4';

            return `
            <group>
              <rect draggable="true" style={{width: ${width}, height: 40, fill: '#DAE2E4', radius: 4}} keyshape>
                <text style={{ fontSize: 16, marginLeft: 12, marginTop: 12, fill: '#4f515b' }}>${cfg.label}</text>
              </rect>
            </group>
          `;
          },
          getAnchorPoints() {
            return [
              [0, 0.5],
              [1, 0.5],
            ];
          },
        },
        'single-node',
      );
      // 一级节点
      G6.registerNode(
      'dice-mind-map-sub', {
        jsx: (cfg) => {
          const width = Util.getTextSize(cfg.label, 16)[0] + 24;
          const stroke = cfg.style.stroke || '#DAE2E4';
          const color = cfg.color || cfg.style.stroke;
          const fill = cfg.style.fill || '#DAE2E4';

          return `
          <group>
            <rect draggable="true" style={{width: ${width}, height: 40, fill: ${fill}, radius: 4}} keyshape>
              <text style={{ fontSize: 16, marginLeft: 12, marginTop: 12, fill: '#fff' }}>${cfg.label}</text>
            </rect>
          </group>
        `;
        },
        getAnchorPoints() {
          return [
            [0, 0.5],
            [1, 0.5],
          ];
        },
      },
      'single-node',
    );
      // 叶子节点
      G6.registerNode(
        'dice-mind-map-leaf', {
          jsx: (cfg) => {
            const width = Util.getTextSize(cfg.label, 12)[0] + 24;
            const stroke = cfg.style.stroke || '#DAE2E4';
            const color = cfg.color || cfg.style.stroke;
            const fill = cfg.style.fill || '#DAE2E4';

            return `
            <group>
              <rect draggable="true" style={{width: ${width}, height: 40, stroke: '#5DB0F3', radius: 2}} keyshape>
                <text style={{ fontSize: 12, marginLeft: 12, marginTop: 12, fill: '#4f515b' }}>${cfg.label}</text>
              </rect>
            </group>
          `;
          },
          getAnchorPoints() {
            return [
              [0, 0.5],
              [1, 0.5],
            ];
          },
        },
        'single-node',
      );
      G6.registerBehavior('dice-mindmap', {
        getEvents() {
          return {
            'node:click': 'clickNode',
            'node:dblclick': 'editNode',
            'node:mouseenter': 'hoverNode',
            'node:mouseleave': 'hoverNodeOut',
          };
        },
        hoverNode(evt) {
          evt.currentTarget.updateItem(evt.item, {
            hover: true,
          });
        },
        hoverNodeOut(evt) {
          evt.currentTarget.updateItem(evt.item, {
            hover: false,
          });
        },
      });
    },
    getData() {
      this.emptyText = 'loading'
      this.$get(this.$Url.team.getRelCompaniesAtlas, {
        pid: this.info.key,
        companyName: this.info.companyName
      }).then(res => {
        let data = res.data
        this.data = data || {}
        
        let keys = Object.keys(data)
        if (keys.length <= 0) {
          this.emptyText = '暂无数据'
        }
        let nodes = {
          id: '0',
          label: this.info.name,
          children: []
        }
        keys.forEach((v, i) => {
          // 
          if (this.data[v]) {
            let str = ''
            if (v === '法人') {
              str = '0-1-'
            } else if (v === '任职') {
              str = '0-2-'
            } else if (v === '高管') {
              str = '0-3-'
            } else if (v === '股东') {
              str = '0-4-'
            }
            data[v].forEach((b, j) => {
              b['label'] = b['name']
              b['id'] = str + j
            })
            // 
            let obj = {
              children: data[v]
            }
            if (v === '法人') {
              obj = {
                ...obj,
                id: '0-1',
                label: '法人',
                style: {
                  fill: '#2fc890'
                }
              }
            } else if (v === '任职') {
              obj = {
                ...obj,
                id: '0-2',
                label: '任职',
                style: {
                  fill: '#B968C7'
                }
              }
            } else if (v === '高管') {
              obj = {
                ...obj,
                id: '0-3',
                label: '高管',
                style: {
                  fill: '#2196F3'
                }
              }
            } else if (v === '股东') {
              obj = {
                ...obj,
                id: '0-4',
                label: '股东',
                style: {
                  fill: '#FD9703'
                }
              }
            }
            nodes.children.push(obj)
          }
        })
        this.renderChart(nodes)
      }).catch(err => {})
    },
    renderChart(nodes) {
      const { Util } = G6
      const dataTransform = (data) => {
        const changeData = (d, level = 0, color) => {
          const data = {
            ...d,
          };
          switch (level) {
            case 0:
              data.type = 'dice-mind-map-root';
              break;
            case 1:
              data.type = 'dice-mind-map-sub';
              break;
            default:
              data.type = 'dice-mind-map-leaf';
              break;
          }

          data.hover = false;

          if (color) {
            data.color = color;
          }

          if (level === 1 && !d.direction) {
            if (!d.direction) {
              data.direction = d.id.charCodeAt(d.id.length - 1) % 2 === 0 ? 'right' : 'left';
            }
          }

          if (d.children) {
            data.children = d.children.map((child) => changeData(child, level + 1, data.color));
          }
          return data;
        };
        return changeData(data);
      };

      let width = document.getElementById('atlas').scrollWidth
      let height = document.getElementById('atlas').scrollHeight || 400
      const graph = new G6.TreeGraph({
        container: 'atlas',
        width,
        height,
        // fitView: true,
        fitViewPadding: [10, 20],
        minZoom: 0.5,
        modes: {
          default: [
            'collapse-expand',
            // 'dice-mindmap',
            'drag-canvas',
            'zoom-canvas',
          ]
        },
        layout: {
          type: 'mindmap',
          direction: 'H',
          getHeight: () => {
            return 16
          },
          getWidth: (node) => {
            return node.level === 0 ?
              Util.getTextSize(node.label, 16)[0] + 12 :
              Util.getTextSize(node.label, 12)[0];
          },
          getVGap: () => {
            return 20
          },
          getHGap: () => {
            return 60;
          },
          getSide: (node) => {
            return node.data.direction;
          },
        },
        defaultEdge: {
          type: 'cubic-horizontal',
          // type: 'polyline',
          style: {
            // offset: 20,
            // radius: 4,
            lineWidth: 2,
            stroke: '#4f515b'
          },
        },
      })

      graph.edge((edge) => {
        let model = edge.source.getModel()
        let id = model.id
        return {
          id: edge.id,
          style: {
            stroke: id === '0'
              ? '#FD9703'
              : '#4f515b'
          }
        }
      })
      
      graph.data(dataTransform(nodes))
      graph.render()
      graph.fitCenter()
    }
  },
  mounted() {
    this.init()
  }
}
</script>

<style lang="scss" scoped>
#atlas {
  width: 100%;
  height: 400px;
}
.no-data {
  line-height: 1.5rem;
}
</style>